import {Button, Card, Divider, Empty, Space, Tag, Typography} from "antd";
import {
    ArrowDownOutlined,
    DatabaseOutlined,
    DeleteOutlined,
    DownCircleOutlined,
    EditOutlined,
    EyeInvisibleOutlined,
    EyeOutlined,
    LockOutlined,
    PlusOutlined,
    UpCircleOutlined,
    UserOutlined
} from "@ant-design/icons";
import {useEffect, useState} from "react";
import NacosConfigAddModal from "./NacosConfigAddModal";
import RequestUtils from "../../utils/RequestUtils";
import Apis from "../../configs/Apis";
import {useNavigate} from "react-router-dom";
import NacosConfigEditModal from "./NacosConfigEditModal";
import "highlight.js/styles/github.css";
import hljs from "highlight.js/lib/core";
import yaml from "highlight.js/lib/languages/yaml";

// 初始化代码高亮
hljs.registerLanguage('yaml', yaml);

const {Title, Text} = Typography;

const NacosConfigList = (props) => {
    const {
        messageApi,
        nacosConfigs,  // nacos配置（仅保留一个元素）
        yamlContent    // YAML配置内容，作为页面主体
    } = props;

    const navigate = useNavigate();
    const [nacosConfigAddParam, setNacosConfigAddParam] = useState({
        visible: false,
        editVisible: false,
        addNacosConfigReq: {
            nacosConfigId: "",      // id
            nacosAddress: "",       // 地址
            nacosNamespace: "",     // 命名空间
            nacosAccount: "",       // 账号
            nacosPassword: "",      // 密码
            nacosDescription: ""    // 描述
        }
    });

    // 管理密码的显示状态
    const [passwordVisible, setPasswordVisible] = useState({});
    // 控制连接信息的展开/折叠状态，默认折叠
    const [connectionInfoExpanded, setConnectionInfoExpanded] = useState(false);

    // 切换密码显示状态
    const togglePasswordVisibility = (id) => {
        setPasswordVisible(prev => ({
            ...prev,
            [id]: !prev[id]
        }));
    };

    // 切换连接信息展开状态
    const toggleConnectionInfo = () => {
        setConnectionInfoExpanded(!connectionInfoExpanded);
    };

    // 为不同命名空间生成不同的标签颜色
    const getNamespaceColor = (namespace) => {
        const colors = ['blue', 'purple', 'green', 'orange', 'pink', 'geekblue', 'cyan', 'lime'];
        let hash = 0;
        for (let i = 0; i < namespace.length; i++) {
            hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
            hash |= 0; // 转换为32位整数
        }
        return colors[Math.abs(hash) % colors.length];
    };

    // 加密密码显示
    const maskPassword = (password) => {
        if (!password) return '无密码信息';
        return '*'.repeat(password.length);
    };

    /**
     * 添加nacos配置
     * @param param
     */
    const doAddNacosConfig = (param) => {
        RequestUtils.post(Apis.Nacos.addNacosConfig, {
            nacosAddress: param.nacosAddress,
            nacosNamespace: param.nacosNamespace,
            nacosAccount: param.nacosAccount,
            nacosPassword: param.nacosPassword,
            nacosDescription: param.nacosDescription
        })
            .then(res => {
                messageApi.success("添加nacos配置成功");
                navigate(0);
            })
            .catch(err => messageApi.error("添加nacos配置失败" + err.message))
    }

    /**
     * 编辑nacos配置
     * @param param
     */
    const doEditNacosConfig = (param) => {
        RequestUtils.post(Apis.Nacos.editNacosConfig, {
            nacosConfigId: param.nacosConfigId,
            nacosAddress: param.nacosAddress,
            nacosNamespace: param.nacosNamespace,
            nacosAccount: param.nacosAccount,
            nacosPassword: param.nacosPassword,
            nacosDescription: param.nacosDescription
        }).then(res => {
            messageApi.success("修改nacos配置成功");
            navigate(0);
        }).catch(err => messageApi.error("修改nacos配置失败" + err.message))
    }

    /**
     * 删除nacos配置
     * @param id
     */
    const doDeleteNacosConfig = (id) => {
        RequestUtils.post(Apis.Nacos.deleteNacosConfigById, {
            id: id
        }).then(res => {
            messageApi.success("删除nacos配置成功");
            navigate(0);
        }).catch(err => messageApi.error("删除nacos配置失败" + err.message))
    }

    /**
     * 同步yaml配置到数据库
     */
    const doSyncYaml2Database = () => {
        RequestUtils.post(Apis.Nacos.syncYamlToDatabase, {})
            .then(res => messageApi.success("同步yaml到数据库成功"))
            .catch(err => messageApi.error("同步yaml到数据库失败" + err.message))
    }

    // 代码高亮效果处理
    useEffect(() => {
        const codeBlocks = document.querySelectorAll('pre code');
        codeBlocks.forEach(block => {
            hljs.highlightElement(block);
        });
    }, [yamlContent]);

    return (
        <div className="nacos-config-list-container" style={{
            padding: '20px',
            backgroundColor: '#f5f7fa',
        }}>
            {/* 头部区域 */}
            <div className="header-section" style={{
                marginBottom: '20px',
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                backgroundColor: 'white',
                padding: '16px 20px',
                borderRadius: '12px',
                boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)'
            }}>
                <div className="page-title" style={{
                    fontSize: '24px',
                    fontWeight: 600,
                    color: '#1a1a2e',
                    display: 'flex',
                    alignItems: 'center'
                }}>
                    <DatabaseOutlined style={{marginRight: '10px', color: '#40a9ff'}}/>
                    Nacos配置管理
                </div>

                <div style={{display: 'flex', gap: '12px'}}>
                    <Button
                        onClick={() => doSyncYaml2Database()}
                        style={{
                            backgroundColor: '#CC0066',
                            border: 'none',
                            padding: '8px 20px',
                            borderRadius: '8px',
                            fontSize: '14px',
                            fontWeight: 500,
                            transition: 'all 0.3s ease',
                            boxShadow: '0 4px 12px rgba(204, 0, 102, 0.3)',
                            color: 'white'
                        }}
                        icon={<ArrowDownOutlined/>}
                    >
                        同步yaml配置到数据库
                    </Button>

                    {nacosConfigs.length > 0 ? (
                        <Button
                            type="primary"
                            onClick={() => setNacosConfigAddParam({
                                ...nacosConfigAddParam,
                                editVisible: true,
                                addNacosConfigReq: nacosConfigs[0]
                            })}
                            style={{
                                padding: '8px 20px',
                                borderRadius: '8px',
                                fontSize: '14px',
                                fontWeight: 500,
                                transition: 'all 0.3s ease'
                            }}
                            icon={<EditOutlined/>}
                        >
                            编辑配置
                        </Button>
                    ) : (
                        <Button
                            type="primary"
                            onClick={() => setNacosConfigAddParam({
                                ...nacosConfigAddParam,
                                visible: true
                            })}
                            style={{
                                padding: '8px 20px',
                                borderRadius: '8px',
                                fontSize: '14px',
                                fontWeight: 500,
                                transition: 'all 0.3s ease'
                            }}
                            icon={<PlusOutlined/>}
                        >
                            创建配置
                        </Button>
                    )}
                </div>
            </div>

            {/* 配置列表区域 */}
            <div className="config-list-section">
                {nacosConfigs.length > 0 ? (
                    <Card
                        hoverable
                        bordered={false}
                        borderRadius={12}
                    >
                        {/* 连接信息区域 - 默认折叠 */}
                        <div>
                            <Button
                                type="text"
                                onClick={toggleConnectionInfo}
                                style={{
                                    width: '100%',
                                    justifyContent: 'center',
                                    padding: '12px',
                                    color: '#40a9ff',
                                    fontSize: '14px'
                                }}
                            >
                                {connectionInfoExpanded ? (
                                    <>
                                        <UpCircleOutlined style={{marginRight: '8px'}}/>
                                        收起 Nacos 连接配置详情信息
                                    </>
                                ) : (
                                    <>
                                        <DownCircleOutlined style={{marginRight: '8px'}}/>
                                        点此查看 Nacos 连接配置详情信息
                                    </>
                                )}
                            </Button>

                            {/* 展开时显示连接详情 */}
                            <div style={{
                                overflow: 'hidden',
                                transition: 'max-height 0.3s ease',
                                maxHeight: connectionInfoExpanded ? '500px' : '0'
                            }}>
                                <div style={{padding: '0 20px 20px 20px'}}>
                                    <Divider style={{margin: '10px 0'}}/>

                                    {/* 配置地址区域 */}
                                    <div style={{marginBottom: '16px'}}>
                                        <div style={{display: 'flex', alignItems: 'center'}}>
                                            <DatabaseOutlined
                                                style={{
                                                    fontSize: 16,
                                                    color: '#40a9ff',
                                                    marginRight: 8,
                                                    backgroundColor: 'rgba(64, 169, 255, 0.1)',
                                                    padding: 4,
                                                    borderRadius: 6
                                                }}
                                            />
                                            <div style={{
                                                fontWeight: 500,
                                                fontSize: 14,
                                                color: '#1a1a2e',
                                                maxWidth: 'calc(100% - 30px)',
                                                whiteSpace: 'nowrap',
                                                overflow: 'hidden',
                                                textOverflow: 'ellipsis'
                                            }}>
                                                {nacosConfigs[0].nacosAddress}
                                                <a
                                                    target={'_blank'}
                                                    rel="noopener noreferrer"
                                                    style={{marginLeft: '20px', color: '#40a9ff', borderBottom: '1px solid #40a9ff'}}
                                                    href={`${nacosConfigs[0].nacosAddress}/nacos/`}
                                                >
                                                    前往nacos控制台
                                                </a>
                                            </div>
                                        </div>
                                    </div>

                                    {/* 命名空间区域 */}
                                    <div style={{marginBottom: '16px'}}>
                                        <div style={{
                                            color: '#667085',
                                            marginBottom: 6,
                                            fontSize: '13px'
                                        }}>命名空间
                                        </div>
                                        <Tag
                                            color={getNamespaceColor(nacosConfigs[0].nacosNamespace)}
                                            bordered={false}
                                            style={{
                                                borderRadius: 6,
                                                padding: '3px 8px',
                                                fontSize: '12px',
                                                fontWeight: 500
                                            }}
                                        >
                                            {nacosConfigs[0].nacosNamespace}
                                        </Tag>
                                    </div>

                                    {/* 账号区域 */}
                                    <div style={{marginBottom: '16px'}}>
                                        <div style={{
                                            color: '#667085',
                                            marginBottom: 6,
                                            fontSize: '13px',
                                            display: 'flex',
                                            alignItems: 'center'
                                        }}>
                                            <UserOutlined style={{marginRight: 4, fontSize: 12}}/>
                                            账号
                                        </div>
                                        <div style={{
                                            color: '#344054',
                                            wordBreak: 'break-all'
                                        }}>
                                            {nacosConfigs[0].nacosAccount || '无账号信息'}
                                        </div>
                                    </div>

                                    {/* 密码区域 */}
                                    <div style={{marginBottom: '16px'}}>
                                        <div style={{
                                            color: '#667085',
                                            marginBottom: 6,
                                            fontSize: '13px',
                                            display: 'flex',
                                            alignItems: 'center'
                                        }}>
                                            <LockOutlined style={{marginRight: 4, fontSize: 12}}/>
                                            密码
                                        </div>
                                        <div style={{
                                            color: '#344054',
                                            wordBreak: 'break-all',
                                            display: 'flex',
                                            alignItems: 'center'
                                        }}>
                      <span style={{flexGrow: 1}}>
                        {passwordVisible[nacosConfigs[0].id] ? nacosConfigs[0].nacosPassword || '无密码信息' : maskPassword(nacosConfigs[0].nacosPassword)}
                      </span>
                                            <Button
                                                type="text"
                                                size="small"
                                                icon={passwordVisible[nacosConfigs[0].id] ? <EyeInvisibleOutlined/> :
                                                    <EyeOutlined/>}
                                                onClick={() => togglePasswordVisibility(nacosConfigs[0].id)}
                                                style={{
                                                    padding: '0 4px',
                                                    marginLeft: 8,
                                                    color: '#40a9ff',
                                                    fontSize: '14px'
                                                }}
                                            />
                                        </div>
                                    </div>

                                    {/* 描述信息 */}
                                    {nacosConfigs[0].nacosDescription && (
                                        <div style={{marginBottom: '16px'}}>
                                            <div style={{
                                                color: '#667085',
                                                marginBottom: 6,
                                                fontSize: '13px'
                                            }}>
                                                描述
                                            </div>
                                            <div style={{
                                                color: '#344054',
                                                wordBreak: 'break-all',
                                                backgroundColor: 'rgba(64, 169, 255, 0.05)',
                                                padding: '8px 12px',
                                                borderRadius: '6px',
                                                borderLeft: '3px solid #40a9ff'
                                            }}>
                                                {nacosConfigs[0].nacosDescription}
                                            </div>
                                        </div>
                                    )}

                                    {/* 操作按钮区域 */}
                                    <Space size="small"
                                           style={{width: '100%', justifyContent: 'flex-end', marginTop: 16}}
                                    >
                                        <Button
                                            size="small"
                                            type="text"
                                            icon={<EditOutlined/>}
                                            style={{
                                                color: '#52c41a',
                                                padding: '4px 12px',
                                                borderRadius: '4px',
                                                transition: 'all 0.2s ease',
                                                '&:hover': {
                                                    backgroundColor: 'rgba(82, 196, 26, 0.1)',
                                                    color: '#389e0d'
                                                }
                                            }}
                                            onClick={() => setNacosConfigAddParam({
                                                ...nacosConfigAddParam,
                                                editVisible: true,
                                                addNacosConfigReq: {
                                                    nacosConfigId: nacosConfigs[0].id,
                                                    nacosAddress: nacosConfigs[0].nacosAddress,
                                                    nacosNamespace: nacosConfigs[0].nacosNamespace,
                                                    nacosAccount: nacosConfigs[0].nacosAccount,
                                                    nacosPassword: nacosConfigs[0].nacosPassword,
                                                    nacosDescription: nacosConfigs[0].nacosDescription,
                                                }
                                            })}
                                        >
                                            编辑
                                        </Button>
                                        <Button
                                            size="small"
                                            type="text"
                                            danger
                                            icon={<DeleteOutlined/>}
                                            style={{
                                                color: '#ff4d4f',
                                                padding: '4px 12px',
                                                borderRadius: '4px',
                                                transition: 'all 0.2s ease',
                                                '&:hover': {
                                                    backgroundColor: 'rgba(255, 77, 79, 0.1)',
                                                    color: '#cf1322'
                                                }
                                            }}
                                            onClick={() => doDeleteNacosConfig(nacosConfigs[0].id)}
                                        >
                                            删除
                                        </Button>
                                    </Space>
                                </div>
                            </div>
                        </div>
                    </Card>
                ) : (
                    <div style={{
                        textAlign: 'center',
                        padding: '60px 20px',
                        backgroundColor: 'white',
                        borderRadius: 12,
                        margin: '20px 0',
                        boxShadow: '0 2px 8px rgba(0, 0, 0, 0.06)',
                        transition: 'all 0.3s ease'
                    }}>
                        <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description={
                                <div style={{
                                    color: '#667085',
                                    marginTop: 16,
                                    fontSize: '16px'
                                }}>
                                    未查询到nacos配置信息
                                </div>
                            }
                            style={{margin: 0}}
                        >
                            <Button
                                type="primary"
                                size="middle"
                                onClick={() => setNacosConfigAddParam({
                                    ...nacosConfigAddParam,
                                    visible: true
                                })}
                                style={{
                                    borderRadius: 6,
                                    padding: '8px 24px',
                                    fontSize: 14,
                                    backgroundColor: '#40a9ff',
                                    border: 'none',
                                    boxShadow: '0 4px 12px rgba(64, 169, 255, 0.3)',
                                    transition: 'all 0.3s ease',
                                    '&:hover': {
                                        transform: 'translateY(-2px)',
                                        boxShadow: '0 6px 16px rgba(64, 169, 255, 0.4)',
                                        backgroundColor: '#1890ff'
                                    }
                                }}
                                icon={<PlusOutlined/>}
                            >
                                立即创建配置
                            </Button>
                        </Empty>
                    </div>
                )}
            </div>

            {/* 新增nacos配置modal */}
            <NacosConfigAddModal
                messageApi={messageApi}
                nacosConfigAddParam={nacosConfigAddParam}
                setNacosConfigAddParam={setNacosConfigAddParam}
                doAddNacosConfig={doAddNacosConfig}
            />

            {/* 编辑nacos配置modal */}
            <NacosConfigEditModal
                messageApi={messageApi}
                nacosConfigAddParam={nacosConfigAddParam}
                setNacosConfigAddParam={setNacosConfigAddParam}
                doEditNacosConfig={doEditNacosConfig}
            />
        </div>
    );
};

export default NacosConfigList;